﻿using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using Baggr.FeedParser.Atom;
using Baggr.FeedParser.Rss;

namespace Baggr.FeedParser
{
    /// <summary>
    /// Вспомогательный класс для работы с фидами.
    /// </summary>
    public static class FeedHelper
    {
        public static IFeed GetFeed(this XmlReader reader)
        {
            if (!reader.ReadToElement())
                throw new FormatException();
            Type feedType;
            switch(reader.Name)
            {
                case "rss":
                    feedType = typeof (RssFeed);
                    break;
                case "feed":
                    feedType = typeof (AtomFeed);
                    break;
                default:
                    throw new FormatException();
            }

            var desializer = new XmlSerializer(feedType, "Baggr");
            desializer.UnknownAttribute += desializer_UnknownAttribute;
            desializer.UnknownElement += desializer_UnknownElement;
            return (IFeed)desializer.Deserialize(reader);
        }

        static void desializer_UnknownElement(object sender, XmlElementEventArgs e)
        {
        }

        static void desializer_UnknownAttribute(object sender, XmlAttributeEventArgs e)
        {
        }

        private static bool ReadToElement(this XmlReader reader)
        {
            while (reader.Read())
            {
                if (reader.NodeType == XmlNodeType.Element)
                    return true;
            }
            return false;
        }
    }
}


